import Styles from './index.module.scss'
import React, { useEffect, useRef, useState } from 'react'
import Icon from '../icon'
type Props = {
  className?: string
  src: string
  alt?: string
}
export default function Image({ className, src, alt }: Props) {
  const imgRef = useRef<HTMLImageElement>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(false)
  const current = imgRef.current!
  useEffect(() => {
    const observe = new IntersectionObserver(function ([{ isIntersecting }]) {
      if (isIntersecting) {
        current.src = current.dataset.src as string
        observe.unobserve(current)
      }
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  return (
    <div className={Styles.root}>
      <img
        data-src={src}
        alt={alt}
        // onLoading={() => {
        //   setError(false)
        //   setLoading(true)
        // }}
        ref={imgRef}
        onError={() => {
          setError(true)
          setLoading(false)
        }}
      />
    </div>
  )
}
